#include<iostream>
#include<math.h>
#include<unordered_map>
using namespace std;
struct Thing
{
	int num, wei, lim, put;
};
int Change(int& tmp)
{
	int result = 0;
	for (int i = 0; i < 32; i++)
	{
		if (tmp & 1)
		{
			result += pow(2, i);
		}
		tmp = tmp >> 1;
	}
	return result;
}
int main()
{
	int n, total, num, wei, lim, put;
	cin >> n;
	unordered_map<int, Thing>m;
	for (int i = 0; i < n; i++)
	{
		m.clear();
		cin >> total;
		for (int j = 0; j < total; j++)
		{
			Thing t;
			cin >> t.num >> t.wei >> t.lim >> t.put;
			//先全部存到map里
			m.insert(pair<int, Thing>(t.num, t));
		}
		bool flag = false;
		vector<vector<bool>>mat;
		mat.resize(total);
		for (auto& g : mat) { g.resize(total); }
		for (vector<bool>& g : mat)
		{
			for (int a = 0; a < total; a++) { g[a] = false; }
		}
		for (pair<int, Thing>g : m)
		{

			//无论是背包还是物品，都要追溯更新
			//追溯
			int tm = 0;
			while (g.second.put != -1)
			{
				auto tmp = m.find(g.second.put);
				//背包之间如果加过那就加差值好了
				if (mat[g.second.num][g.second.put] == false)
				{
					mat[g.second.num][g.second.put] = true;
					tmp->second.wei += g.second.wei;
					tm = g.second.wei;
				}
				else
				{
					tmp->second.wei += tm;
				}
				
				
				if (tmp->second.wei > tmp->second.lim) { flag = true; break; }
				g = *tmp;
			}
			if (flag) { cout << 0 << endl; break; }

		}
		if (flag) { continue; }
		else { cout << 1 << endl; }
	}
}